<?php
class TicketServer {
	public function pagingBySearch($where="",$order='',$numberEachPage = 10,$page_search = array()){
		$count = HttpDaoManager::getTicketDao()->searchMutilNumber($where);
		if(isset($page_search)&&!empty($page_search)){
			$page = new Page($count, $numberEachPage,$page_search['page_par']);
		}else{
			$page = new Page($count, $numberEachPage);
		}
		$limit[0]= $page->which;
		$limit[1]=$numberEachPage;
		$list = HttpDaoManager::getTicketDao()->searchMutilList($where,$order, $limit);
		if(isset($page_search)&&!empty($page_search)){
			$page1= $page->returnPage("?".$page_search['page_par']."=");
		}else{
			$page1= $page->returnPage("?".ClassManager::getToos()->combinationGet('page')."&page=");
		}
		$data['list'] =$list;
		$data['page'] = $page1;
		return $data;
	}
	
	public function generateNumber($data){
		$startNumber = $data['startNumber'];
		$quantity = $data['quantity'];
		$prefix = $data['prefix'];
		$suffix = $data['suffix'];
		$randDigits = $data['randDigits'];
		$numberDigits = $data['numberDigits'];
		$cryptMethod = $data['cryptMethod'];
		//$cryptMethod =  empty($cryptMethod)?'md5':$cryptMethod;
		$passwordLeng = $data['passwordLeng'];
		$i=0;
		$tmpc  = array();
		while ($i<$quantity){
			$i++;
			$number = $prefix.$this->digits($numberDigits, $startNumber).$suffix.$this->randByBecrypt($randDigits);
			$startNumber++;
        	if (!empty($cryptMethod)) {			
				$tmp = $cryptMethod($number);
				$tmp = strtr($tmp, '+/=', '059');
				$password = $this->encrypt(substr($tmp, mt_rand(0, max(strlen($tmp) - $passwordLeng, 0)), $passwordLeng));
				$tmpc[]= array('number' => $number,'password' => $password);
        	}else{
				$tmpc[]= array('number' => $number,'password' => '');
        	}
		}
		return $tmpc;
	}
	public function generate($data){
		$tmp  = $this->generateNumber($data);
		$tmpc = array ();
		$addTime = time();
		$addAdmin = $_SESSION['admin']['name'];
		$valid_start_time = strtotime($data['valid_start_time']);
		$valid_end_time = strtotime($data['valid_end_time']);
		$tmpe = array();
		$verifier = "";
		foreach($tmp as $v){
			$tmpe[] = "'".$v['number']."'";
			if(!empty($v['password'])){
				$info = array();
				$info['number'] = $v['number'];
				$info['password'] = $v['password'];
				$info['add_time'] = $addTime;
				$verifier = $this->getVerifier($info);
			}	
			$tmpc[] = array(
				'number' => $v['number'],
				'password'  => $v['password'],
				'add_time' => $addTime,
				'add_admin'  => $addAdmin,
				'valid_start_time' => $valid_start_time,
				'valid_end_time' => strtotime("+1 day ",$valid_end_time)-1,
				'product_id' => $data['product_id'],
				'verifier'=>$verifier
			);
		}
		
		$ticketDao  =HttpDaoManager::getTicketDao();
		$number = implode(',',$tmpe);
		$tmpf = $ticketDao->getByNumber($number);
		if (!empty($tmpf)){
			return ERROR_CODE_11;
		}
		$ticketDao->add($tmpc);
		$ticketList = $ticketDao->getByNumberList($number);
		$tmpd = array();
		foreach ($ticketList as $v){
			$tmpd[] = array(
				'ticket_id' => $v['id'],
				'add_time' => $addTime,
				'add_admin'  => $addAdmin,
			);
		}
		HttpDaoManager::getTicketLogDao()->add($tmpd);
		return true;
	}
	
	public function  exportData($data_list){
		$data = array();
		if(!empty($data_list['list'])){
			foreach($data_list['list'] as $key=>$value){
				$verifier = "";
				$data[$key]['number']=$value['number'];
				$data[$key]['password']=$value['password'];
				if(!empty($value['verifier'])){
					$verifier = self::getVerifier($value);
		            if ($value['verifier'] != $verifier) {
		                return;
		            }	
				}
				if(!empty($value['password'])){
		            $data[$key]['raw_password'] = $this->decrypt($value['password']);			
				}
			}
		}
		return $data;
	}
	
	public function validateCardInfo($ticket_info,$password){
		if($ticket_info['status']!=TICKET_STATUS_2){//
			return ERROR_CODE_11;//无效卡
		}else{
			if(time()>$ticket_info['valid_start_time']&&time()<=$ticket_info['valid_end_time']){
				if($ticket_info['verifier']!= self::getVerifier($ticket_info)){
					return ERROR_CODE_12;
				}else{
					$ticket_passowrd = $ticket_info['password'];
					$decrypt_password = $this->decrypt($ticket_passowrd);
					if($decrypt_password==$password){
						return true;						
					}else{
						return ERROR_CODE_13;
					}
				}
			}else{
				return ERROR_CODE_FOUR;//过期卡
			}			
		}		
	}
	
	public function validateCardLogInfo($ticket_log_info){
		if($ticket_log_info['use_user_id']!=0){
			return ERROR_CODE_SIX;//已使用
		}
		return true;
	}
	
	
	public function useCardInfo($ticket_info){
		$use_log_info['use_user_id'] = $_SESSION['user']['id'];	
		$use_log_info['use_user'] = $_SESSION['user']['english_name'];
		$use_log_info['use_time'] = time();
		
		$use_info['status'] = TICKET_STATUS_3;
		$ticket_id = $ticket_info['id'];
		$use_ticket_info['status'] = TICKET_STATUS_3;
		HttpDaoManager::getTicketDao()->updateById($use_ticket_info,$ticket_id);
		HttpDaoManager::getTicketLogDao()->updateByTicketId($use_log_info,$ticket_id);
		//充值
	}
	
	public function digits($digits , $v){
		$tmp =$digits -   strlen($v);
		$i=0;
		$tmpa ='';
		while ($i<$tmp){
			$i++;
			$tmpa = '0'.$tmpa;
		}
		return $tmpa.$v;
	}


    private  function getVerifier($info)
    {
        return crc32($info['number'] . $info['password'] . $info['add_time'] . PASSWORDPREFIX);
    }
	
	public  function encrypt($str, $key =PASSWORDPREFIX){
		$coded = '';
		$keylength = strlen($key);
		for ($i = 0, $count = strlen($str); $i < $count; $i += $keylength) {
			$coded .= substr($str, $i, $keylength) ^ $key;
		}
		return str_replace('=', '', base64_encode($coded));
	}
	
	public  function decrypt($str, $key =PASSWORDPREFIX)
	{
		$coded = '';
		$keylength = strlen($key);
		$str = base64_decode($str);
	
		for ($i = 0, $count = strlen($str); $i < $count; $i += $keylength) {
			$coded .= substr($str, $i, $keylength) ^ $key;
		}
	
		return $coded;
	}
	public function randByBecrypt($digits){
		if($digits>0){
			$i = 0;
			$tmpa= '';
			while ($i<$digits-1){
				$i++;
				$tmpa = '0'.$tmpa;
			}
			$tmpa = '1'.$tmpa;
			$tmpb = '';
			$i=0;
			while ($i<$digits){
				$i++;
				$tmpb = '9'.$tmpb;
			}
			$a =  rand($tmpa, $tmpb);
		}
		return $a;
	}
	public function activation($id){

		if (is_array($id)){
			$activationTime = time();
			$activationAdmin = $_SESSION['admin']['name'] ;
			$data = array(
				'activation_time' => $activationTime,
				'activation_admin' => $activationAdmin,
				'status' => TICKET_STATUS_2
			);
			$tmpa = implode(',',$id);
			HttpDaoManager::getTicketDao()->updates($data,$tmpa);
			$data = array(
				'activation_time' => $activationTime,
				'activation_admin' => $activationAdmin,
			);
			HttpDaoManager::getTicketLogDao()->updatesByTicketIdList($data, $tmpa);
		}
	}
	
	public function cancellation($id){
		if (is_array($id)){
			$data['status'] = TICKET_STATUS_4;
			$tmpa = implode(',',$id);
			HttpDaoManager::getTicketDao()->updates($data,$tmpa);
			$data = array(
				'cancellation_time' => time(),
				'cancellation_admin' =>  $_SESSION['admin']['name']
			);
			HttpDaoManager::getTicketLogDao()->updates($data, $tmpa);
		}
	}
	public function batchSend($user,$ticket){
		$product_info = HttpDaoManager::getProductDao()->get($ticket['product_id']);
		if(empty($product_info)){
			return ERROR_CODE_13;
		}
		
		$userData = HttpDaoManager::getUserDao()->searchMutilList($user);
		$userCount = count($userData);
		if($userCount==0){
			return ERROR_CODE_13;
		}
		
		$ticket_where['status'] = TICKET_STATUS_1;//代金券自由激活，无需人工激活
		$ticket_where['receive_user_id'] =0;
		$ticket_where['product_id']=$product_info['id'];
		$now_time = time();
		$ticket['valid_end_time'] = array(time(),'>');
		
		$ticketDao = HttpDaoManager::getTicketDao();
		$ticketData = $ticketDao->searchList($ticket_where,'',$userCount);
		if ($userCount>count($ticketData)){
			return ERROR_CODE_12;
		}
		
		$sendTime = time();
		foreach ($userData as $k => $v){
			$this->activation(array($ticketData[$k]['id']));//发放前激活
			$data['receive_user_id'] =$v['id'];
			$data['id'] = $ticketData[$k]['id'];
			$data['valid_end_time'] = strtotime("+ ".$product_info['period_validity']." day",time());//更新有效期
			$tmp['send_admin'] = $_SESSION['admin']['name'];
			$tmp['send_time'] = $sendTime;
			$this->update($data, $tmp);
		}
		return true;
	}
	
	public function favourTicketSend($user_id,$return_product_id,$num){
		$product_info = HttpDaoManager::getProductDao()->get($return_product_id);
		if(empty($product_info)){
			return;
		}	
		$ticket_where = array();
		$ticket_where['status'] = TICKET_STATUS_1;//未激活的
		$ticket_where['receive_user_id'] =0;
		$ticket_where['product_id']=$product_info['id'];
		$now_time = time();
		$ticket['valid_end_time'] = array(time(),'>');		
		$ticketDao = HttpDaoManager::getTicketDao();
		$ticketData = $ticketDao->searchList($ticket_where,'',1);
		
		if($num>count($ticketData)){
			return;
		}
		$ticket_id =$ticketData[0]['id'];	
		$this->activation(array($ticket_id));//发放前激活

		$sendTime = time();
		$data = array();
		$data['receive_user_id'] =$user_id;
		$data['id'] = $ticketData[0]['id'];
		$data['valid_end_time'] = strtotime("+ ".$product_info['period_validity']." day",time());//更新有效期
		$tmp['send_admin'] ='system';
		$tmp['send_time'] = $sendTime;//发放
		$this->update($data, $tmp);

	}
	
	public function update($ticketData,$logData){
		HttpDaoManager::getTicketDao()->updateById($ticketData,$ticketData['id']);
		HttpDaoManager::getTicketLogDao()->updateByTicketId($logData, $ticketData['id']);
	}
	public function getVoucher($userId){
		$productDao = HttpDaoManager::getProductDao() ;
		$product = $productDao->searchList(array('type'=>PRODUCT_TYPE_3));
		if(!empty($product)){
			$tmp = array();
			foreach ($product as $v){
				$tmp[] = $v['id'];
			}
			$tmp = implode(',',$tmp);
			$where['product_id'] = array($tmp,'in');
			$where['receive_user_id'] = $userId;
			$time=  time();
			$where['valid_start_time'] = array($time,'<=');
			$where['valid_end_time'] = array($time,'>=');
			$where['status'] = TICKET_STATUS_2;
			$list =  HttpDaoManager::getTicketDao()->searchList($where);
			foreach ($list as $k=>$v){
				$tmpa = $productDao->get($v['product_id']);
				$list[$k]['price'] = $tmpa['price'];
			}
		}
		return $list;
	}
	public function getVoucher1($userId,$number){
		$productDao = HttpDaoManager::getProductDao() ;
		$product = $productDao->searchList(array('type'=>PRODUCT_TYPE_3));
		$tmp = array();
		foreach ($product as $v){
			$tmp[] = $v['id'];
		}
		$tmp = implode(',',$tmp);
		$where['product_id'] = array($tmp,'in');
		$where['receive_user_id'] = $userId;
		$time=  time();
		$where['valid_start_time'] = array($time,'<=');
		$where['valid_end_time'] = array($time,'>=');
		$where['status'] = TICKET_STATUS_2;
		$where['number'] = $number;
		return   HttpDaoManager::getTicketDao()->searchList($where);
	}
	public function validation($userId,$number){
		$where['receive_user_id'] = $userId;
		$where['number'] = $number;
		$where['status'] = TICKET_STATUS_2;
		$where['valid_start_time'] = array(time(),'<=');
		$where['valid_end_time'] = array(time(),'>=');
		return HttpDaoManager::getTicketDao()->searchData($where);
		
		
	}
	public function exchange($product_id, $user_id){
		$productData = HttpDaoManager::getProductDao()->get($product_id);
		$ticketData =  HttpDaoManager::getTicketDao()->searchData(array('product_id'=>$product_id,'status'=>TICKET_STATUS_2,'receive_user_id'=>"''"));
		if (!empty($ticketData)){
			$ticketData['receive_user_id'] =$user_id;
			$time = strtotime(date(('Y-m-d')))+86400;
			$ticketData['valid_start_time'] = $time;
			$ticketData['valid_end_time'] = $time + $productData['period_validity']*86400;
			$logData['send_time'] = time();
			$this->update($ticketData, $logData);
			return true;
		}
		else{
			return USER_ERROR_17;
		}
	}
	public function uses($id,$orderId){
		$tickerDao  = HttpDaoManager::getTicketDao();
		$ticketdata  = $tickerDao->get($id);
		$ticketdatas['status'] = TICKET_STATUS_3;
		$tickerDao->updates($ticketdatas, $id);
		$userData = HttpDaoManager::getUserDao()->get($ticketdata['receive_user_id']);
		$ticketLogData['use_user']  = $userData['english_name'];
		$ticketLogData['use_user_id'] = $ticketdata['receive_user_id'];
		$ticketLogData['use_time'] = time();
		$ticketLogData['order_id'] = $orderId;
		HttpDaoManager::getTicketLogDao()->updateByTicketId($ticketLogData, $id);
	}
}

?>